package com.example.campuslink.ui.fragment

import android.annotation.SuppressLint
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.recyclerview.widget.GridLayoutManager
import com.example.campuslink.BR
import com.example.campuslink.R
import com.example.campuslink.commen.adpter.PhotoAdapter
import com.example.campuslink.commen.tools.VideoUtil
import com.example.campuslink.databinding.FragmentPhotoBinding
import com.example.campuslink.model.ChoiceFilePathData
import com.example.campuslink.viewModel.PhotoViewModel

class PhotoFragment : BaseFragment<FragmentPhotoBinding, PhotoViewModel>(
    PhotoViewModel::class.java,
    R.layout.fragment_photo,
    BR.viewModel
) {
    private val fileType: Array<String> = arrayOf("照片", "视频")
    private lateinit var adapter: ArrayAdapter<String>
    private lateinit var photoAdapter: PhotoAdapter
    override fun onClick() {
        mViewDataBinding?.spinnerShowFileType?.setOnItemSelectedListener(object :
            AdapterView.OnItemSelectedListener {
            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                mViewModel?.setFileType(fileType[p2])
            }

            override fun onNothingSelected(p0: AdapterView<*>?) {

            }
        })
        mViewDataBinding?.tvNext?.setOnClickListener({
            mViewModel?.jumpToPublicActivity()
        })
    }

    override fun initViews() {
        photoAdapter = PhotoAdapter(mViewModel!!)
        mViewDataBinding?.rvPhotoShow?.adapter = photoAdapter
        mViewDataBinding?.rvPhotoShow?.layoutManager = GridLayoutManager(requireContext(), 3)
        val adapter =
            ArrayAdapter<String>(requireContext(), android.R.layout.simple_spinner_item, fileType)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        mViewDataBinding?.spinnerShowFileType?.setAdapter(adapter)
        mViewDataBinding?.freshLayout?.setOnRefreshListener {
            when (mViewModel?.fileType?.value) {
                "照片" -> {
                    readAlbumImages()
                }

                "视频" -> {
                    val videoList = VideoUtil().getLocalVideoList(requireContext())
                    isOnChoice(videoList.toMutableList())
                    photoAdapter.setListData(videoList)
                }
            }
            mViewDataBinding?.freshLayout?.isRefreshing = false
        }

    }

    fun isOnChoice(list: MutableList<ChoiceFilePathData>) {
        val currentList = mViewModel?.allFilePath?.value ?: mutableListOf()
        val path = currentList.filter { it.isChoice }.map { it.path }
//        Log.i("TAG", "isOnChoice: ${path}")
        list.forEach {
            it.isChoice = it.path in path
        }
    }

    override fun initData() {
        mViewModel?.context = requireContext()
//        allImagePath =
//            Sp.getStringArray(requireContext(), SpKey.IMAGE_PATH.key, arrayOf())?.toMutableList()
//                ?: mutableListOf()
//        if (allImagePath != null) {
//            mViewModel?.setIsShowNext(true)
//        }
        mViewModel?.allFilePath?.observe(this) {
            if (it.size > 0) {
                mViewDataBinding?.tvNext?.isEnabled = true
                mViewDataBinding?.tvNext?.visibility = View.VISIBLE
            }
        }
        mViewModel?.fileType?.observe(this) {
            when (it) {
                "照片" -> {
                    readAlbumImages()
                }

                "视频" -> {
                    val videoList = VideoUtil().getLocalVideoList(requireContext())
                    isOnChoice(videoList.toMutableList())
                    photoAdapter.setListData(videoList)
                }
            }
        }
    }

    private fun readAlbumImages() {
        val imagePaths: MutableList<String> = ArrayList()
        val projection = arrayOf(MediaStore.Images.Media.DATA)
        val cursor = activity?.contentResolver?.query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            projection, null, null, null
        )
        if (cursor != null) {
            while (cursor.moveToNext()) {
                @SuppressLint("Range") val imagePath =
                    cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
                imagePaths.add(imagePath)
            }
            cursor.close()
        }
        val temp: MutableList<ChoiceFilePathData> = ArrayList()
        for (i in imagePaths.indices.reversed()) {
            temp.add(ChoiceFilePathData(imagePaths.get(i), false))
        }
        isOnChoice(temp)
        photoAdapter.setListData(temp)
    }
}